/*============================================================================
 * Copyright 2009 VMware Inc.
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at: http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions and limitations 
 * under the License.
 ============================================================================*/

package com.vmware.vcloud.tmrk;

import java.io.IOException;
import java.net.MalformedURLException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import com.vmware.vcloud.VCloudObject;
import com.vmware.vcloud.data.XmlBuilder;
import com.vmware.vcloud.rest.RestClient;

/**
 * @author Steve Jin (sjin@vmware.com)
 */

public class PublicIpAddress extends VCloudObject
{
	String id = null;
	
	public PublicIpAddress(RestClient rc, String href) throws MalformedURLException
	{
		super(rc, href);
	}
	
	public PublicIpAddress(RestClient rc, String href, String name, String id) throws MalformedURLException
	{
		super(rc, href, name);
		this.id = id;
		this.root = NON_EMPTY_ELEMENT; //tell getter methods not getting xml again
	}
	
	@Override
	protected void parse() 
	{
		name = root.elementText("Name");
	}
	
	public String getIp() throws IOException
	{
		this.loadContentIfNotYet();	
		return name;
	}
	
	public InternetService addInternetService(String name, String protocol, int port, String description) throws MalformedURLException, IOException
	{
		String reqBody = XmlBuilder.buildAddInternetServiceReq(name, protocol, port, description);
		
		String resBody = rc.post(this.getURL()+"/internetServices", reqBody, "application/xml");
		
		try
		{
		Document doc = DocumentHelper.parseText(resBody);
	    String id = doc.getRootElement().elementText("Id");
	    String href = "https://services.vcloudexpress.terremark.com/api/v0.8/" + "internetServices/" + id;
		return new InternetService(rc, href);
		}
		catch(DocumentException de)
		{
			throw new RuntimeException(de);
		}
	}
	
	public void delete() throws IOException 
	{
		rc.delete(getURL());
	}
	
	public InternetService[] getInternetServices()
	{
		return new InternetService[0];
		//TODO
	}
	
}
